<template>
  <div class="page flex-column">
    <div class="page-title">计算作业</div>
    <div class="task-filter flex-row">
      <div class="total-info flex-row">
        <div class="total-data flex-column">
          <div class="total-title">计算资源</div>
          <div class="total-detail flex-row flex-center">
            <item-info itemTitle="内存" :itemData="overviewSource.memory"></item-info>
            <item-info itemTitle="处理器" :itemData="overviewSource.cpu"></item-info>
            <item-info itemTitle="磁盘" :itemData="overviewSource.disk"></item-info>
            <item-info itemTitle="任务队列" :itemData="(overviewSource.queueTask ? overviewSource.queueTask : 0) + ' 个'"></item-info>
          </div>
        </div>
        <div class="total-chart flex-column flex-center">
          <div class="circle-chart">
            <a-progress type="circle" :percent="overviewSource.cpuUsed" :format="percent => `CPU ${percent}%`" />
          </div>
        </div>
      </div>
      <div class="total-space"></div>
      <div class="account-info flex-column">
        <div class="account-title">我的账户</div>
        <div class="account-extitle">使用期限</div>
        <div class="account-exinfo flex-row flex-center-end">
          <div class="account-exicon">
            <ClockCircleOutlined :style="{ fontSize: '30px', color: '#999999' }" />
          </div>
          <div class="account-exdate">{{ overviewSource.deadline }}  截止</div>
        </div>
      </div>
    </div>
    <div class="task-result flex-column">
      <div class="result-search">
        <div class="result-title">
          <a-radio-group v-model:value="searchTaskType" @change="doSearch()">
            <a-radio-button value="1">当前作业</a-radio-button>
            <a-radio-button value="2">历史作业</a-radio-button>
          </a-radio-group>
        </div>
        <div v-if="searchTaskType!='1'" class="result-condition">
          <div class="slt-status">
            <a-select
              ref="select"
              v-model:value="statusValue"
              :options="statusOptions"
              @change="changeStatus"
              placeholder="全部状态"
              style="width: 120px"
            ></a-select>
          </div>
          <div class="rpk-date">
            <a-range-picker
              v-model:value="dateRange"
              :format="dateFormat"
              style="width: 100%; height: 100%;" />
          </div>
          <div class="btn-search">
            <a-button danger shape="round"
              @click="doSearch()"
              style="width: 100%; height: 100%;">
              查询
            </a-button>
          </div>
        </div>
      </div>

      <!-- 表单区 -->
      <div v-if="isNotEmpty(storeComputeTask.computeTaskSource)" class="result-list">
        <a-table
          :columns="columns"
          :data-source="storeComputeTask.computeTaskSource"
          :pagination="false"
          style="width: 100%"
          >
          <template #headerCell="{ column }">
            <span> {{ column.title }} </span>
          </template>

          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'jobId'">
              <span>
                {{ record.jobId }}
              </span>
            </template>
            <template v-if="column.key === 'jobName'">
              <span>
                {{ record.jobName }}
              </span>
            </template>
            <template v-else-if="column.key === 'username'">
              <span>
                {{ record.username }}
              </span>
            </template>
            <template v-else-if="column.key === 'param1'">
              <span>
                {{ record.param1 }}
              </span>
            </template>
            <template v-else-if="column.key === 'startTime'">
              <span>
                {{ record.startTime }}
              </span>
            </template>
            <template v-else-if="column.key === 'runningTime'">
              <span>
                {{ formatSeconds(record.runningTime) }}
              </span>
            </template>
            <template v-else-if="column.key === 'status'">
              <span :style="'color: ' + getStatusColor(record.status)">
                {{ getStatusText(record.status) }}
              </span>
            </template>
            <template v-else-if="column.key === 'action'">
              <span>
                <a :href="scnetViewTaskUrl" @click.prevent="getScnetViewTaskUrl" target="_blank"><img src="./img/open.png" /></a>
              </span>
            </template>
          </template>
        </a-table>
      </div>

      <!-- 空列表 -->
      <div v-else class="empty-list">
        <div class="empty-box">
          <img src="@/assets/images/empty-task.png" />
          <div class="empty-tip">
            <div class="empty-label">还没有计算作业，</div>
            <div class="empty-btn">
              <a :href="scnetConsoleUrl" @click.prevent="getScnetConsoleUrl" target="_blank">
                <text-button label="去控制台提交" color="#E8423A" size="16">
                  <template #right>
                    <CaretRightOutlined />
                  </template>
                </text-button>
              </a>
            </div>
          </div>
        </div>
      </div>

      <div v-if="searchTaskType!='1' && totalRecords>pageSize" class="task-pagination flex-row flex-center">
        <a-pagination 
          v-model:current="currentPage"
          v-model:pageSize="pageSize"
          :total="totalRecords"
          @change="storeComputeTask.handlePageChange"
          show-less-items />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onBeforeMount } from 'vue';
import type { SelectProps } from 'ant-design-vue';
import { message } from 'ant-design-vue';
import { ClockCircleOutlined, CaretRightOutlined } from '@ant-design/icons-vue';
import dayjs, { Dayjs } from 'dayjs';
import { isNotEmpty, formatSeconds } from "@/utils";
import ItemInfo from './components/ItemInfo.vue';
import useComputeTaskStore from '@/stores/compute-task';
import appConfig from '@/config';
import { miscApi } from "@/services";

const searchTaskType = ref<string>('1');

const statusValue = ref('');
const statusOptions = ref<SelectProps['options']>([
  { value: '', label: '全部状态' },
  { value: 'statC', label: '完成' },
  { value: 'statE', label: '退出' },
  { value: 'statDE', label: '取消' },
  { value: 'statD', label: '失败' },
  { value: 'statT', label: '超时' },
  { value: 'statN', label: '节点异常' },
  { value: 'statRQ', label: '重新运行' },
]);
const currentStatus = {
  'statR': '运行',
  'statQ': '排队',
  'statH': '保留',
  'statS': '挂起',
  'statW': '等待',
  'statX': '其他',
};
const statusMap = statusOptions.value.reduce((map, item) => {
  map[item.value] = item.label;
  return map;
}, {});
const getStatusText = (status: string) => {
  return statusMap[status] ? statusMap[status] : (currentStatus[status] ? currentStatus[status] : `未知状态${status}`);
};
const statusColor = {
  statR: '#28C155',
  statQ: '#999999',
  statH: '#999999',
  statS: '#FF4927',
  statE: '#999999',
  statC: '#666666',
  statW: '#1A98FF',
  statD: '#FF4927',
  statX: '#999999',
};
const getStatusColor = (status: string) => {
  return statusColor[status] ? statusColor[status] : '#FF4927';
};
const changeStatus: SelectProps['onChange'] = value => {
  console.log("changeStatus value: ", value);
  statusValue.value = value? value.toString() : '';
};

const dateFormat = 'YYYY-MM-DD';
const getDate = (date: Dayjs) => {
  return date.format(dateFormat);
}
const defaultDateRange = ref<[Dayjs, Dayjs]>([
  dayjs().subtract(1, 'year'),
  dayjs()
]);
const dateRange = ref<[Dayjs, Dayjs]>();

const storeComputeTask = useComputeTaskStore();
const currentPage = ref<number>(storeComputeTask.pageNum);
const pageSize = ref<number>(storeComputeTask.pageSize);
const totalRecords = ref<number>(storeComputeTask.totalRecords);

const columns = [
  {
    title: "ID",
    dataIndex: "jobId",
    key: "jobId",
    width: "5%",
  },
  {
    title: "任务名称",
    dataIndex: "jobName",
    key: "jobName",
    width: "30%",
  },
  {
    title: "所属用户",
    dataIndex: "username",
    key: "username",
    width: "10%",
  },
  {
    title: "求解器",
    dataIndex: "param1",
    key: "param1",
    width: "10%",
  },
  {
    title: "开始时间",
    dataIndex: "startTime",
    key: "startTime",
    width: "15%",
  },
  {
    title: "运行时间",
    dataIndex: "runningTime",
    key: "runningTime",
    width: "15%",
  },
  {
    title: "任务状态",
    dataIndex: "status",
    key: "status",
    width: "10%",
  },
  {
    title: "操作",
    dataIndex: "action",
    key: "action",
    width: "5%",
  },
];

const overviewSource = ref({});
onBeforeMount(async () => {
  setSearchParams();
  await storeComputeTask.initData();

  overviewSource.value = storeComputeTask.overviewSource;

  await miscApi.traceViewPage("/my-task/list");
});

const doSearch = async () => {
  if (dateRange.value && dateRange.value[0].valueOf() > dateRange.value[1].valueOf()) {
    message.error("开始日期不能大于结束日期");
    return;
  }

  setSearchParams();
  if (searchTaskType.value === '1') {
    await storeComputeTask.getMyCurrentList();
  } else {
    await storeComputeTask.handleSearch();
  }

  // 更新记录数
  totalRecords.value = storeComputeTask.totalRecords;
};
const setSearchParams = () => {
  storeComputeTask.status = statusValue.value;
  storeComputeTask.startDate = dateRange.value ? getDate(dateRange.value[0]) : getDate(defaultDateRange.value[0]);
  storeComputeTask.endDate = dateRange.value ? getDate(dateRange.value[1]) : getDate(defaultDateRange.value[1]);
  storeComputeTask.pageNum = currentPage.value;
  storeComputeTask.pageSize = pageSize.value;
}

const scnetConsoleUrl = ref("");
const scnetViewTaskUrl = ref("");
const getScnetConsoleUrl = async () => {
  scnetConsoleUrl.value = await miscApi.getRedirectUrl(appConfig.scnetConsole);
  window.open(scnetConsoleUrl.value, '_blank');
}
const getScnetViewTaskUrl = async () => {
  scnetViewTaskUrl.value = await miscApi.getRedirectUrl(appConfig.scnetViewTask);
  window.open(scnetViewTaskUrl.value, '_blank');
}
</script>

<style lang="less" scoped>
.page {
  margin: 0;
  padding: 0;
  width: 100%;
  height: 100%;
  background-color: @white-bg;

  .page-title {
    height: 24px;
    line-height: 24px;
    font-size: 20px;
    font-weight: 500;
    color: @font-black;
    padding: 20px 30px;
  }

  .task-filter {
    height: 194px;
    border-radius: 20px;
    margin: 20px 30px 0px 30px;

    .total-info {
      flex: 1;
      background: @white;
      border-radius: 20px;
      padding: 20px;

      .total-data {
        flex: 1;

        .total-title {
          height: 16px;
          line-height: 16px;
          font-size: 16px;
          font-weight: 500;
          color: @font-black;
        }

        .total-detail {
          margin: 26px;
          justify-content: space-between;
        }
      }
      .total-chart {
        width: 195px;

        .circle-chart {
          width: 130px;
          width: 130px;
          margin: 12px 45px 12px 0;
        }
      }
    }

    .total-space {
      width: 20px;
    }

    .account-info {
      width: 420px;
      background-image: url('./img/account-info-bg.png');
      border-radius: 20px;
      padding: 30px 20px;

      .account-title {
        height: 16px;
        line-height: 16px;
        font-size: 16px;
        font-weight: 500;
        color: @font-black;
      }

      .account-extitle {
        height: 14px;
        line-height: 14px;
        font-size: 14px;
        font-weight: 400;
        color: @font-grey;
        text-align: right;
        margin-top: 30px;
      }

      .account-exinfo {
        height: 34px;
        margin-top: 20px;

        .account-exicon {
          padding: 2px;
        }

        .account-exdate {
          height: 34px;
          line-height: 34px;
          font-size: 34px;
          font-weight: 500;
          color: @font-black;
          margin-left: 10px;
        }
      }
    }
  }
  .task-result {
    background-color: @white;
    border-radius: 20px;
    margin: 20px 30px;

    .result-search {
      height: 24px;
      padding: 20px;
      display: flex;
      flex-direction: row;
      align-items: center;
      justify-items: center;
      margin-top: 20px;

      .result-title {
        flex: 1;
        height: 24px;
        line-height: 24px;
        font-size: 20px;
        font-weight: 500;
        color: @font-black;
      }

      .result-condition {
        width: 600px;
        display: flex;
        justify-content: right;

        .slt-status {
          width: 120px;
        }

        .rpk-date {
          margin-left: 20px;
          width: 300px;
        }

        .btn-search {
          margin-left: 20px;
          width: 100px;
        }
      }
    }

    .result-list {
      margin: 10px 20px 0 20px;
    }

    .empty-list {
      height: 620px;
      display: flex;
      flex-direction: column;
      align-items: center;

      .empty-box {
        width: 420px;
        height: 255px;
        margin-top: 150px;
        position: relative;
        display: flex;
        justify-content: center;

        img {
          width: 100%;
          height: 100%;
        }

        .empty-tip {
          position: absolute;
          bottom: 0px;
          height: 16px;
          line-height: 16px;
          font-size: 16px;
          font-weight: 400;
          display: flex;
          flex-direction: row;
          align-items: center;

          .empty-label {
            color: @font-grey;
          }

          .empty-btn {
            color: @text-link-color;
          }
        }
      }
    }
  }
  .task-pagination {
    width: 100%;
    padding: 30px 20px 50px 20px;
  }
}

:deep(.ant-table-wrapper .ant-table-thead >tr>th) {
  color: @font-black;
  background-color: @pink-table-hd;
}



:deep(.ant-pagination) {
  .ant-pagination-item {
    min-width: 44px;
    height: 44px;
    margin-inline-end: 10px;
    line-height: 44px;
    background-color: @white;
    border: 1px solid @border-red-light;
    border-radius: 50%;

    a {
      font-size: 14px;
      font-weight: 400;
    }

    &.ant-pagination-item-active {
      border: 1px solid #ED171F;
    }
  }
  .ant-pagination-prev, .ant-pagination-next, .ant-pagination-jump-prev, .ant-pagination-jump-next {
    min-width: 44px;
    height: 44px;
    color: @font-black;
    line-height: 44px;
    border: 1px solid @border-red-light;
    border-radius: 50%;
    margin-inline-end: 10px;

    a {
      font-size: 14px;
      font-weight: 400;
      border-radius: 50%;
    }
  }

  .ant-pagination-prev:hover .ant-pagination-item-link, .ant-pagination-next:hover .ant-pagination-item-link {
    background-color: rgba(0, 0, 0, 0.06);
  }

  .ant-pagination-prev .ant-pagination-item-link, .ant-pagination-next .ant-pagination-item-link {
    border-radius: 50%;
  }

  .ant-pagination-options {
    display: none;
  }
}
</style>
